// #ifdef H5
// import jWeixin from 'jweixin-module'
// #endif


// var util = require('@/common/we7_js/util.js');
import util from './we7_js/util.js'

export const isWeiXin = () => {
	let target = navigator?.userAgent.toLowerCase();
	return /micromessenger/.test(target);
}

export const getCode = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			success: async ({
				code
			}) => {
				resolve(code)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

export const payment = (pay_info) => {
	return new Promise((resolve, reject) => {
		const params = pay_info.data ? pay_info.data : pay_info
		// #ifdef MP
		// #ifdef MP-TOUTIAO
		let param = {
			provider: 'toutiao',
			orderInfo: params,
			service: 5
		};
		// #endif
		// #ifdef MP-WEIXIN

		let param = params;
		// #endif

		uni.requestPayment({
			...param,
			success: res => {
				// #ifdef MP-WEIXIN
				resolve()
				// #endif
				// #ifdef MP-TOUTIAO
				if (res.code == 0) {
					resolve()
				} else {
					reject('支付失败')
				}
				// #endif

			},
			fail: err => {
				console.info({
					err
				})
				reject(err)
			}
		});
		// #endif

		// #ifdef H5
		if (isWeiXin()) {
			jWeixin.chooseWXPay({
				...params,
				timestamp: params.timeStamp,
				success: (res) => {
					resolve(true)
				},
				fail: (err) => {
					console.info({
						err
					})
					reject(err)
				}
			});
		} else {
			window.location.href = params.mweb_url
			resolve(true)
		}
		// #endif
	})
}

export const getLocation = () => {
	return new Promise((resolve, reject) => {
		// #ifdef MP || APP-PLUS
		// #ifdef MP-WEIXIN
		// @ts-ignore
		// const locationType = 'getFuzzyLocation';
		// #endif
		// #ifndef MP-WEIXIN
		// @ts-ignore
		// const locationType = 'getLocation';
		//#endif

		const locationType = 'getLocation';

		uni[locationType]({
			type: "gcj02",
			success: (res) => {
				console.info(res)
				resolve(res)
			},
			fail: (err) => {
				console.info({
					err
				})
				uni.showToast({
					title: "请打开手机定位功能再试",
					icon: "error"
				})
				reject(err)
			}
		})
		//#endif

		// #ifdef H5
		if (isWeiXin()) {
			jWeixin.getLocation({
				type: "gcj02",
				success: (res) => {
					resolve(res)
				},
				cancel: (err) => {
					reject()
				},
				fail: (err) => {
					console.info('officon location error:', err)
					uni.showToast({
						title: "请打开手机定位功能再试",
						icon: "error"
					})
					reject(err)
				},
			});
		} else {
			uni.getLocation({
				type: "gcj02",
				success: (res) => {
					resolve(res)
				},
				fail: (err) => {
					uni.showToast({
						title: "请打开手机定位功能再试",
						icon: "error"
					})
					reject(err)
				}
			})
		}
		//#endif
	})
}

